import {
    message,
    Tooltip,
} from 'antd';
import React from 'react';
import moment from "moment";
import { stringify } from 'qs';

/**
 * Mr.Tool's Util JavaScript.
 * @Author 肖家添
 * @Date 2019/8/20 15:01
 */

const APP = {

    TOKEN_KEY: "MYRCIB_USER_TOKEN",

    /**
     * 判断object是否为空, [true]: 不为空, [false]: 为空
     * @Author 肖家添
     * @Date 2019/8/20 14:45
     */
    isValidObj: function(obj){
        if(obj == null || (obj + "") == "" || (obj + "").length <= 0 || obj == undefined){
            return false;
        }

        return true;
    },

    /**
     * [按钮] -> 样式
     * @Author 肖家添
     * @Date 2019/8/19 19:42
     */
    buttonsStyle_MR15: {
        style: {
            marginRight: '15px',
        }
    },

    /**
     * [表格] -> 行选中事件
     * @Author 肖家添
     * @Date 2019/8/20 14:45
     */
    tableRowSelection: function(callback, selectedKeys){
        return {
            selectedRowKeys: selectedKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                if(APP.isValidObj(callback)){
                    callback(selectedRowKeys, selectedRows);
                }
            }
        };
    },

    /**
     * 验证JSON里面的value是否为空，为空则删除
     * @Author 肖家添
     * @Date 2019/8/23 9:41
     */
    validNilParams: function(json = {}){
        for(let key in json){
            const val = json[key];

            if(!APP.isValidObj(val) || val == undefined){
                delete json[key];
            }
        }
    },

    /**
     * JSON合并
     * @Author 肖家添
     * @Date 2019/8/23 9:44
     */
    jsonMerge: function(jsonO ={}, jsonT = {}){
        let cloneJSON = JSON.parse(JSON.stringify(jsonO));

        for(const key in jsonT){
            cloneJSON[key] = jsonT[key];
        }

        return cloneJSON;
    },

    /**
     * 读取图片的Base64
     * @Author 肖家添
     * @Date 2019/8/23 15:56
     */
    getImageFileBase64: function(originFileObj, callback) {
        const reader = new FileReader();
        reader.addEventListener("load", () => callback(reader.result));
        reader.readAsDataURL(originFileObj);
    },

    /**
     * wangEditor编辑器默认内容
     * @Author 肖家添
     * @Date 2019/8/24 10:14
     */
    wangEditorDefaultContent: `<p><br></p>`,

    /**
     * Error提示
     * @Author 肖家添
     * @Date 2019/8/24 11:57
     */
    errorMessage(context, msg){
        context.setState({loading: false});
        message.error(msg);
    },

    /**
     * 打开加载层，前提是页面引用了[spin]组件，state设置了[loading]标识
     * @Author 肖家添
     * @Date 2019/8/24 16:05
     */
    loading: function(context){
        context.setState({loading: true});
    },

    /**
     * 关闭加载层
     * @Author 肖家添
     * @Date 2019/8/24 16:06
     */
    closeLoading: function(context){
        context.setState({loading: false});
    },

    /**
     * 常用于表格的数据状态字段显示
     * @Author 肖家添
     * @Date 2019/8/25 15:41
     */
    isenabledRender: function(text){
        text = text + "";

        switch(text){
            case "-1":{
                return "作废";
            }
            case "0":{
                return "下架";
            }
            case "1":{
                return "正常";
            }
        }

        return text;
    },

    /**
     * 根据表格选中的行，判断是否要提示选择行；通常用于 [编辑/上架/下架/删除]
     * @Author 肖家添
     * @Date 2019/8/27 0:35
     */
    STooltipForKeys: function(selectedTableKeys = [], children, msg = "请先选中数据"){
        return (
            <Tooltip title={selectedTableKeys.length > 0 ? "" : msg}>
                {children}
            </Tooltip>
        );
    },
    /**
     * 客户端域名, 图片地址转换有用, 不可轻易更改此值
     */
    clientDomain: "mtadmin.xiaobaibao.com",
    /**
     * OSS正式环境
     */
    ossDomain_product: "https://xiaobai-image-product.oss-cn-shenzhen.aliyuncs.com/",
    /**
     * OSS测试环境
     */
    ossDomain_dev: "https://xiaobai-image-dev.oss-cn-shenzhen.aliyuncs.com/",
    /**
     * 旧图片兼容处理
     * @Author 肖家添
     * @Date 2019/9/1 18:15
     */
    oldImageHostChange: function(resUrl){
        if(APP.isValidObj(resUrl) && !resUrl.startsWith("https")){
            let prefix = window.location.href;
            if(prefix.indexOf(APP.clientDomain) > -1){
                //-- 正式环境
                prefix = APP.ossDomain_product;
            }else{
                //-- 测试环境
                prefix = APP.ossDomain_dev;
            }
            resUrl = `${prefix}/${resUrl}`;
        }

        return resUrl;
    },

    rangePickerDateFormat: function(values, key){
        const createPeriod = values[key];
        if(createPeriod != null && createPeriod.length > 0){
            let startMoment = createPeriod[0],
                endMoment = createPeriod[1];

            startMoment = moment(startMoment).format("YYYY-MM-DD");
            endMoment = moment(endMoment).format("YYYY-MM-DD");

            values[key] = [startMoment, endMoment];
        }
    },

    /**
     * moment转string类型, 格式 [YYYY-MM-DD HH:mm:ss]
     * @Author 肖家添
     * @Date 2019/11/25 14:49
     */
    momentFormatToStr: function(date, format = "YYYY-MM-DD"){
        return moment(date).format(format);
    },

    /**
     * 日期间隔天数
     * @Author 肖家添
     * @Date 2019/11/25 15:50
     */
    dateMinus: function(date1, date2){
        const sdate = new Date(date1),
            now = new Date(date2),
            days = now.getTime() - sdate.getTime(),
            day = Math.ceil(days / (1000 * 60 * 60 * 24));
        return day;
    },

    /**
     * 异常抛出，终止线程
     * @Author 肖家添
     * @Date 2019/9/18 16:38
     */
    throw: function(msg = "Thread termination"){
        throw msg;
    },

    /**
     * 判断[value]是否为空，为空返回[transfer]内容
     * @Author 肖家添
     * @Date 2019/9/3 20:23
     */
    changeIsNilVal: function(value, transfer){
        if(!APP.isValidObj(value)){
            return transfer;
        }

        return value;
    },

    /**
     * 获取编码
     * @Author 肖家添
     * @Date 2020/3/8 19:56
     */
    getCode: function(prefix) {
      const randomStr = prefix + (
        moment().format("YYYYMMDDHHmm")
      ) + (
        Math.floor(Math.random() * 100000)
      );
      return randomStr;
    },

    /**
     * 数据导出
     * @Author 肖家添
     * @Date 2020/3/16 19:05
     */
    exportData: function({parent, requestUrl, formData = {}, fileNamePrefix = "文件", exportType = 1, tablePagination}){
        const isAntdPro = function() {
            return window.location.hostname === 'preview.pro.ant.design';
        };
        const options = {
            method: 'POST',
            'Content-Type': 'application/json',
            expirys: isAntdPro(),
            credentials: 'include',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json; charset=utf-8',
            },
        };
        const token = sessionStorage.getItem(APP.TOKEN_KEY);
        if (token) {
            options.headers = {
                MYRCIB_USER_TOKEN: token,
                ...options.headers,
            };
        }
        let params = {...formData};
        if (exportType === 1 && APP.isValidObj(tablePagination)) {
            const { _current, _pageSize } = tablePagination;
            params['_current'] = _current;
            params['_pageSize'] = _pageSize;
        } else if (exportType === 2) {
            params['notLimit'] = true;
        }
        APP.loading(parent);
        fetch(`${requestUrl}?${stringify(params)}`, options).then(response => {
            response
                .blob()
                .then(blob => {
                    APP.closeLoading(parent);
                    if (response.status === 200) {
                        let blobUrl = window.URL.createObjectURL(blob);
                        let aElement = document.createElement('a');
                        let filename = fileNamePrefix + Date.parse(new Date()) + '.xls';
                        aElement.href = blobUrl;
                        aElement.download = filename;
                        aElement.click();
                        window.URL.revokeObjectURL(blobUrl);
                    } else {
                        message.error("数据导出请求失败");
                    }
                })
                .catch(e => {
                    APP.closeLoading(parent);
                });
        });
    }
};

export default APP;
